﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiskInspector.Model;
using Microsoft.Win32.SafeHandles;

namespace DiskInspector
{
    public partial class DiskInspectorForm : Form
    {
        private byte[] buffer;

        private static List<ManagementObject> Disks;

        public DiskInspectorForm()
        {
            InitializeComponent();
        }

        private void btn_DisplayClick(object sender, EventArgs e)
        {
            try
            {
                using (var disk = DiskManager.GetStream())
                {
                    long sectorIndex, offset = 0;

                    if (long.TryParse(this.cb_SectorIndex.Text, out sectorIndex))
                    {
                        offset = sectorIndex * DiskManager.SectorSize;
                    }

                    buffer = DiskManager.ReadSector(disk, offset);

                    BinaryBox.Clear();
                    BinaryBox.Refresh();
                    BinaryBox.Text = buffer.ToByteString();
                }
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btn_MBRClick(object sender, EventArgs e)
        {
            try
            {
                using (var disk = DiskManager.GetStream())
                {
                    buffer = DiskManager.ReadSector(disk, 0);
                }

                var MBR = DataParser.Parse<MainBootRecord>(buffer);
                var form = new MainBootRecordForm(this, MBR);
                form.ShowDialog();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DiskInspectorForm_Load(object sender, EventArgs e)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
            ManagementObjectCollection collection = searcher.Get();

            Disks = collection
                .Cast<ManagementObject>()
                .Where(item => (string)item["MediaType"] == "Fixed hard disk media")
                .OrderBy(item => item["Name"])
                .ToList();

            foreach (var item in Disks)
            {
                lb_Drive.Items.Add(item["Model"].ToString());
            }
        }

        private void lb_Drive_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb_Drive.SelectedIndex == -1) return;

            tb_DriveDetails.ResetText();

            DiskManager.SelectedDisk = Disks[lb_Drive.SelectedIndex];
            var properties = DiskManager.SelectedDisk.Properties.Cast<PropertyData>().Where(p => p.Origin == "Win32_DiskDrive").ToList();
            tb_DriveDetails.Lines = properties.Select(property => String.Format("{0}: {1}", property.Name, property.Value)).ToArray();
        }
    }
}
